package com.cq.hd.app.controller;

import com.cq.hd.common.annotation.LoginUser;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.BusinessInfo;
import com.cq.hd.common.entity.UserInfo;
import com.cq.hd.common.enums.biz.AgentStateEnum;
import com.cq.hd.common.enums.biz.NoFullAutoRefundStateEnum;
import com.cq.hd.common.enums.biz.PromotionTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.common.response.Throw;
import com.cq.hd.product.api.TbActiveApi;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.api.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;

@RestController
@RequestMapping("/businessActive")
@Api(tags = "商家活动相关接口")
public class BusinessActiveController {

    @Autowired
    private TbActiveApi activeApi;

    @ApiOperation(value = "校验商品库存")
    @ApiImplicitParam(name = "activeGoodsStockCheckDto", value = "实体", paramType = "body", dataType = "activeGoodsStockCheckDto")
    @PostMapping("/checkGoodsStock")
    public Result<Object> checkGoodsStock(@ApiIgnore @LoginUser AppLoginUser appLoginUser,
                                          @RequestBody @Valid ActiveGoodsStockCheckDto activeGoodsStockCheckDto) {
        return activeApi.checkGoodsStock(activeGoodsStockCheckDto);
    }

    @ApiOperation(value = "发布活动")
    @ApiImplicitParam(name = "activeReleaseDto", value = "实体", paramType = "body", dataType = "ActiveReleaseDto")
    @PostMapping("/release")
    public Result<Object> releaseActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody @Valid ActiveReleaseDto activeReleaseDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            activeReleaseDto.setBusinessId(businessInfo.getId());
        }
        activeReleaseDto.setUserId(appLoginUser.getUserId());

        return activeApi.releaseActive(activeReleaseDto);
    }

    @ApiOperation(value = "发布拼团活动")
    @ApiImplicitParam(name = "groupBuyActiveReleaseDto", value = "实体", paramType = "body", dataType = "GroupBuyActiveReleaseDto")
    @PostMapping("/releaseGroupBuy")
    public Result<Object> releaseGroupBuyActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody @Valid GroupBuyActiveReleaseDto groupBuyActiveReleaseDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            groupBuyActiveReleaseDto.setBusinessId(businessInfo.getId());
        }
        groupBuyActiveReleaseDto.setUserId(appLoginUser.getUserId());
        groupBuyActiveReleaseDto.setPromotionType(PromotionTypeEnum.GROUP_BUY.name());
        // 不限制报名人数，所以关闭未满自动退
        groupBuyActiveReleaseDto.setNoFullAutoRefundState(NoFullAutoRefundStateEnum.NO.getValue());
        return activeApi.releaseGroupBuyActive(groupBuyActiveReleaseDto);
    }

    @ApiOperation(value = "我的活动列表")
    @ApiImplicitParam(name = "appMyActivePageDto", value = "实体", paramType = "query", dataType = "AppMyActivePageDto")
    @ApiResponse(response = AppMyActivePageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageMyActive")
    public Result<Page<AppMyActivePageVo>> pageMyActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, AppMyActivePageDto appMyActivePageDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appMyActivePageDto.setBusinessId(businessInfo.getId());
        }
        appMyActivePageDto.setUserId(appLoginUser.getUserId());

        return activeApi.pageMyActive(appMyActivePageDto);
    }

    @ApiOperation(value = "修改活动")
    @ApiImplicitParam(name = "activeUpdateDto", value = "实体", paramType = "body", dataType = "ActiveUpdateDto")
    @PutMapping("/update")
    public Result<Object> updateActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody ActiveUpdateDto activeUpdateDto) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            activeUpdateDto.setBusinessId(businessInfo.getId());
        }
        activeUpdateDto.setUserId(appLoginUser.getUserId());

        return activeApi.updateActive(activeUpdateDto);
    }

    @ApiOperation(value = "我的活动详情(去发布)")
    @ApiImplicitParam(name = "id", value = "活动id", paramType = "query", dataType = "Long")
    @ApiResponse(response = AppMyActiveDetailsVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/myActiveDetails")
    public Result<AppMyActiveDetailsVo> myActiveDetails(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestParam(value = "id") Long id) {
        AppMyActiveDetailsVo activeDetailsVo = activeApi.myActiveDetails(id).unpack();
        if (activeDetailsVo != null) {
            BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
            if (businessInfo != null) {
                activeDetailsVo.setBusinessName(businessInfo.getBusinessName());
                activeDetailsVo.setBusinessShortName(businessInfo.getBusinessShortName());
                activeDetailsVo.setLogo(appLoginUser.getUserInfo().getBusinessInfo().getLogo());
            }
        }
        return ResultGenerator.success(activeDetailsVo);
    }

    @ApiOperation(value = "删除活动")
    @ApiImplicitParam(name = "id", value = "活动id", paramType = "query", dataType = "Long")
    @DeleteMapping("/delete")
    public Result<Object> deleteActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, Long id) {
        Long businessId = null;
        Long userId = appLoginUser.getUserId();
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessId = businessInfo.getId();
        }

        return activeApi.deleteActive(id, userId, businessId);
    }

    @ApiOperation(value = "活动下架")
    @ApiImplicitParam(name = "id", value = "活动id", paramType = "query", dataType = "Long")
    @PostMapping("/down")
    public Result<Object> takeDownActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, Long id) {
        Long businessId = null;
        Long userId = appLoginUser.getUserId();
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessId = businessInfo.getId();
        }

        return activeApi.takeDownActive(id, userId, businessId);
    }

    // 活动预分享（根据活动id，判断用户分享是否可以分佣，如果可以分佣，则判断活动是否有推广奖励(固定佣金和其他权益)，如果有，则返回佣金(优先专属佣金)和其他权益）
    @ApiOperation(value = "活动预分享")
    @ApiImplicitParam(name = "activePreShareDto", value = "实体", required = true, paramType = "body", dataType = "ActivePreShareDto")
    @ApiResponse(response = ActivePreShareVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/preShare")
    public Result<ActivePreShareVo> preShareActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody ActivePreShareDto activePreShareDto) {
        UserInfo userInfo = appLoginUser.getUserInfo();
        Long agent1Id = 0L;
        Long agent2Id = 0L;
        if (userInfo != null && userInfo.getAgentState().equals(AgentStateEnum.OPEN.getValue())) {
            if (userInfo.getAgentId() != null && userInfo.getAgentId() > 0) {
                agent1Id = userInfo.getAgentId();
                agent2Id = userInfo.getId();
            } else {
                agent1Id = userInfo.getId();
            }
        }
        activePreShareDto.setAgent1Id(agent1Id);
        activePreShareDto.setAgent2Id(agent2Id);
        activePreShareDto.setUserId(appLoginUser.getUserId());
        return activeApi.preShareActive(activePreShareDto);
    }

    @ApiOperation(value = "活动分享")
    @ApiImplicitParam(name = "activeShareDto", value = "实体", required = true, paramType = "body", dataType = "ActiveShareDto")
    @ApiResponse(response = ActiveShareVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/share")
    public Result<ActiveShareVo> shareActive(@ApiIgnore @LoginUser AppLoginUser appLoginUser, @RequestBody ActiveShareDto activeShareDto) {
        activeShareDto.setUserId(appLoginUser.getUserId());
        activeShareDto.setNickName(appLoginUser.getUserInfo().getNickName());
        activeShareDto.setAvatar(appLoginUser.getUserInfo().getAvatar());
        UserInfo userInfo = appLoginUser.getUserInfo();
        Long agent1Id = 0L; // 一级经纪人id
        Long agent2Id = 0L; // 二级经纪人id
        if (userInfo != null && userInfo.getAgentState().equals(AgentStateEnum.OPEN.getValue())) {
            if (userInfo.getAgentId() != null && userInfo.getAgentId() > 0) {
                agent1Id = userInfo.getAgentId();
                agent2Id = userInfo.getId();
            } else {
                agent1Id = userInfo.getId();
            }
        }
        activeShareDto.setAgent1Id(agent1Id);
        activeShareDto.setAgent2Id(agent2Id);
        return activeApi.shareActive(activeShareDto);
    }


    @ApiOperation(value = "活动短链生成")
    @PostMapping("/generateShortLink")
    public Result<String> generateShortLink(@ApiIgnore @LoginUser AppLoginUser appLoginUser,
                                            @Valid @RequestBody ActiveShortLinkDto activeShortLinkDto) {
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            Throw.isBusinessException("请先登录");
        }
        return activeApi.generateShortLink(activeShortLinkDto);
    }

}